/**
 * 智慧社区管理系统 - 移动端用户管理API接口
 * @author Wu.Liang
 * @date 2025-01-21
 * @description 移动端工程位于smart-community-app文件夹，严格遵循架构总览中的项目结构规范
 */

import request from '@/api/request'

// 用户信息管理API
export const userInfoApi = {
  // 获取当前用户信息
  getCurrentUser: () => {
    return request.get('/api/user/current')
  },

  // 更新用户信息
  updateUserInfo: (data) => {
    return request.put('/api/user/info', data)
  },

  // 移动端更新用户个人资料
  updateUserProfile: (data) => {
    return request.put('/api/user/mobile/profile/update', data)
  },

  // 获取用户详情
  getUserDetail: (userId) => {
    return request.get(`/api/user/${userId}`)
  },

  // 上传用户头像
  uploadAvatar: (file, uploadType = 'USER_AVATAR', uploadSource = 'APP', remark = '用户头像') => {
    return request.upload('/api/user/avatar', file, 'file', { 
      uploadType, 
      uploadSource, 
      remark 
    })
  },

  // 删除用户头像
  deleteAvatar: () => {
    return request.delete('/api/user/avatar')
  },

  // 获取用户关联的物业公司列表
  getUserPropertyCompanies: (userId) => {
    return request.get(`/api/user/property-companies/user/${userId}`)
  }
}

// 用户认证API
export const userAuthApi = {
  // 用户登录
  login: (data) => {
    return request.post('/api/auth/login', data)
  },

  // 用户登出
  logout: () => {
    return request.post('/api/auth/logout')
  },

  // 刷新token
  refreshToken: (refreshToken) => {
    return request.post('/api/auth/refresh', { refreshToken })
  },

  // 修改密码
  changePassword: (data) => {
    return request.put('/api/auth/password', data)
  },

  // 重置密码
  resetPassword: (data) => {
    return request.post('/api/auth/password/reset', data)
  },

  // 发送验证码
  sendVerificationCode: (phone) => {
    return request.post('/api/auth/verification-code', { phone })
  },

  // 验证验证码
  verifyCode: (phone, code) => {
    return request.post('/api/auth/verify-code', { phone, code })
  }
}

// 用户权限API
export const userPermissionApi = {
  // 获取用户权限列表
  getUserPermissions: (userId) => {
    return request.get(`/api/user/${userId}/permissions`)
  },

  // 获取用户角色列表
  getUserRoles: (userId) => {
    return request.get(`/api/user/${userId}/roles`)
  },

  // 获取用户菜单权限
  getUserMenuPermissions: (userId) => {
    return request.get(`/api/user/${userId}/menu-permissions`)
  },

  // 获取用户数据权限
  getUserDataPermissions: (userId) => {
    return request.get(`/api/user/${userId}/data-permissions`)
  },

  // 检查用户权限
  checkUserPermission: (permission) => {
    return request.post('/api/user/check-permission', { permission })
  }
}

// 用户安全API
export const userSecurityApi = {
  // 绑定手机号
  bindPhone: (data) => {
    return request.post('/api/user/security/bind-phone', data)
  },

  // 更换手机号
  changePhone: (data) => {
    return request.put('/api/user/security/change-phone', data)
  },

  // 绑定邮箱
  bindEmail: (data) => {
    return request.post('/api/user/security/bind-email', data)
  },

  // 更换邮箱
  changeEmail: (data) => {
    return request.put('/api/user/security/change-email', data)
  },

  // 启用/禁用双因素认证
  toggleTwoFactorAuth: (enabled) => {
    return request.put('/api/user/security/two-factor', { enabled })
  },

  // 获取安全设置
  getSecuritySettings: () => {
    return request.get('/api/user/security/settings')
  },

  // 更新安全设置
  updateSecuritySettings: (data) => {
    return request.put('/api/user/security/settings', data)
  }
}

// 用户登录记录API
export const userLoginRecordApi = {
  // 分页查询登录记录
  getLoginRecordList: (params) => {
    return request.get('/api/user/login-records', { params })
  },

  // 获取登录记录详情
  getLoginRecordDetail: (recordId) => {
    return request.get(`/api/user/login-records/${recordId}`)
  },

  // 获取登录统计
  getLoginStatistics: (params) => {
    return request.get('/api/user/login-records/statistics', { params })
  },

  // 清除登录记录
  clearLoginRecords: () => {
    return request.delete('/api/user/login-records')
  }
}

// 用户通知API
export const userNotificationApi = {
  // 分页查询通知列表
  getNotificationList: (params) => {
    return request.get('/api/user/notifications', { params })
  },

  // 获取通知详情
  getNotificationDetail: (notificationId) => {
    return request.get(`/api/user/notifications/${notificationId}`)
  },

  // 标记通知为已读
  markNotificationRead: (notificationId) => {
    return request.put(`/api/user/notifications/${notificationId}/read`)
  },

  // 标记所有通知为已读
  markAllNotificationsRead: () => {
    return request.put('/api/user/notifications/read-all')
  },

  // 删除通知
  deleteNotification: (notificationId) => {
    return request.delete(`/api/user/notifications/${notificationId}`)
  },

  // 获取通知设置
  getNotificationSettings: () => {
    return request.get('/api/user/notifications/settings')
  },

  // 更新通知设置
  updateNotificationSettings: (data) => {
    return request.put('/api/user/notifications/settings', data)
  }
}

// 用户设置API
export const userSettingApi = {
  // 获取用户设置
  getUserSettings: () => {
    return request.get('/api/user/settings')
  },

  // 更新用户设置
  updateUserSettings: (data) => {
    return request.put('/api/user/settings', data)
  },

  // 获取应用设置
  getAppSettings: () => {
    return request.get('/api/user/settings/app')
  },

  // 更新应用设置
  updateAppSettings: (data) => {
    return request.put('/api/user/settings/app', data)
  },

  // 清除应用缓存
  clearAppCache: () => {
    return request.post('/api/user/settings/clear-cache')
  },

  // 获取应用信息
  getAppInfo: () => {
    return request.get('/api/user/settings/app-info')
  }
}

// 用户工具类
export const userUtils = {
  // 验证手机号
  validatePhone: (phone) => {
    const phoneRegex = /^1[3-9]\d{9}$/
    return phoneRegex.test(phone)
  },

  // 验证邮箱
  validateEmail: (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailRegex.test(email)
  },

  // 验证密码强度
  validatePasswordStrength: (password) => {
    const minLength = 6
    const hasLetter = /[a-zA-Z]/.test(password)
    const hasNumber = /\d/.test(password)
    const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password)
    
    if (password.length < minLength) {
      return { valid: false, message: '密码长度至少6位' }
    }
    
    if (!hasLetter || !hasNumber) {
      return { valid: false, message: '密码必须包含字母和数字' }
    }
    
    return { valid: true, message: '密码强度符合要求' }
  },

  // 格式化用户信息
  formatUserInfo: (userInfo) => {
    return {
      ...userInfo,
      displayName: userInfo.nickname || userInfo.username,
      avatarUrl: userInfo.avatar || '/static/images/default-avatar.png',
      phoneMasked: userInfo.phone ? userInfo.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '',
      emailMasked: userInfo.email ? userInfo.email.replace(/(.{2}).*@/, '$1***@') : ''
    }
  },

  // 获取用户状态文本
  getUserStatusText: (status) => {
    const statusMap = {
      1: '正常',
      0: '禁用',
      2: '待激活',
      3: '已锁定'
    }
    return statusMap[status] || '未知状态'
  },

  // 获取用户状态类型
  getUserStatusType: (status) => {
    const typeMap = {
      1: 'success',
      0: 'error',
      2: 'warning',
      3: 'error'
    }
    return typeMap[status] || 'info'
  }
}

// 移动端用户API
export const mobileUser = {
  // 上传文件
  uploadFile: (file, uploadType = 'OTHER', uploadSource = 'APP') => {
    return request.upload('/api/user/upload', file.path || file.tempFilePath, 'file', {
      uploadType,
      uploadSource
    })
  },

  // 获取文件列表
  getFileList: (params) => {
    return request.get('/api/mobile/user/files', { params })
  },

  // 删除文件
  deleteFile: (fileId) => {
    return request.delete(`/api/mobile/user/files/${fileId}`)
  },

  // 获取文件详情
  getFileDetail: (fileId) => {
    return request.get(`/api/mobile/user/files/${fileId}`)
  },

  // 下载文件
  downloadFile: (fileId) => {
    return request.download(`/api/mobile/user/files/${fileId}/download`)
  },

  // 获取文件预览URL
  getFilePreviewUrl: (fileId) => {
    return request.get(`/api/mobile/user/files/${fileId}/preview`)
  }
}

// 导出缺失的函数
export const updateUserInfo = userInfoApi.updateUserInfo
export const uploadAvatar = userInfoApi.uploadAvatar

// 用户房户管理API
export const getUserHouseholds = async (userId) => {
  try {
    console.log('调用获取用户房户列表API', { userId })
    
    const response = await request.get(`/api/user/households/${userId}`)
    
    console.log('获取用户房户列表API响应:', response)
    
    if (response.code === 200) {
      return {
        code: 200,
        success: true,
        data: response.data,
        message: response.message || '获取成功'
      }
    } else {
      return {
        code: response.code || 500,
        success: false,
        data: null,
        message: response.message || response.msg || '获取失败'
      }
    }
  } catch (error) {
    console.error('获取用户房户列表API调用失败:', error)
    return {
      code: 500,
      success: false,
      data: null,
      message: error.message || '网络错误，请重试'
    }
  }
}

// 绑定房户API
export const bindHousehold = async (userId, householdId) => {
  try {
    console.log('调用绑定房户API', { userId, householdId })
    
    const response = await request.post('/api/user/bind-household', {
      userId,
      householdId
    })
    
    console.log('绑定房户API响应:', response)
    
    if (response.code === 200) {
      return {
        code: 200,
        success: true,
        data: response.data,
        message: response.message || '绑定成功'
      }
    } else {
      return {
        code: response.code || 500,
        success: false,
        data: null,
        message: response.message || response.msg || '绑定失败'
      }
    }
  } catch (error) {
    console.error('绑定房户API调用失败:', error)
    return {
      code: 500,
      success: false,
      data: null,
      message: error.message || '网络错误，请重试'
    }
  }
}

// 获取用户设备列表API
export const getUserDevices = async (userId) => {
  try {
    console.log('调用获取用户设备列表API', { userId })
    
    const response = await request.get(`/api/user/devices/${userId}`)
    
    console.log('获取用户设备列表API响应:', response)
    
    if (response.code === 200) {
      return {
        code: 200,
        success: true,
        data: response.data,
        message: response.message || '获取成功'
      }
    } else {
      return {
        code: response.code || 500,
        success: false,
        data: null,
        message: response.message || response.msg || '获取失败'
      }
    }
  } catch (error) {
    console.error('获取用户设备列表API调用失败:', error)
    return {
      code: 500,
      success: false,
      data: null,
      message: error.message || '网络错误，请重试'
    }
  }
}

// 更新用户设备API
export const updateUserDevice = async (deviceId, deviceData) => {
  try {
    console.log('调用更新用户设备API', { deviceId, deviceData })
    
    const response = await request.put(`/api/user/devices/${deviceId}`, deviceData)
    
    console.log('更新用户设备API响应:', response)
    
    if (response.code === 200) {
      return {
        code: 200,
        success: true,
        data: response.data,
        message: response.message || '更新成功'
      }
    } else {
      return {
        code: response.code || 500,
        success: false,
        data: null,
        message: response.message || response.msg || '更新失败'
      }
    }
  } catch (error) {
    console.error('更新用户设备API调用失败:', error)
    return {
      code: 500,
      success: false,
      data: null,
      message: error.message || '网络错误，请重试'
    }
  }
}

// 默认导出
export default {
  userInfoApi,
  userAuthApi,
  userPermissionApi,
  userSecurityApi,
  userLoginRecordApi,
  userNotificationApi,
  userSettingApi,
  userUtils,
  mobileUser
} 